<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Support\Facades\Config;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class AuthJwt
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Config::set('jwt.user','App\Models\User');
        Config::set('auth.providers.users.model',User::class);
        try{
            if(!$user=\JWTAuth::toUser(\JWTAuth::getToken())){
                return response()->json(['message'=>'无此用户','code'=>400004],404);
            }
        }catch (TokenExpiredException $e){
            return response()->json([
                'code' => 400001,
                'message' => 'token 过期'
            ], $e->getStatusCode());

        }catch (TokenInvalidException $e){
            return response()->json([
                'code' => 400003,
                'message' => 'token 失效'
            ], $e->getStatusCode());
        }catch (JWTException $e){
            return response()->json([
                'code' => 400002,
                'message' => 'token 参数错误'
            ], $e->getStatusCode());
        }

        return $next($request);
    }
}
